package com.digital.aspect;

import com.digital.annotation.AutoFill;
import com.digital.constant.AutoFillConstant;
import com.digital.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class AutoFillAspect
{
    @Pointcut("execution(* com.digital.mapper.*.*(..)) && @annotation(com.digital.annotation.AutoFill)")
    public void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint)
    {
        log.info("开始自动填充");
        //获取切入点方法信息
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        //获取切入点方法上的注解
        AutoFill annotation = methodSignature.getMethod().getAnnotation(AutoFill.class);
        //获取注解的值
        OperationType operationType = annotation.value();
        //获取方法参数列表
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length == 0)
        {
            return;
        }
        //获取实体参数
        Object entity = args[0];
        LocalDateTime now =LocalDateTime.now();
        if(operationType == OperationType.INSERT)
        {
            try
            {
                //反射获取实体参数的setCreateTime方法
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                //反射获取实体参数的setUpdateTime方法
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                setCreateTime.invoke(entity,now);
                setUpdateTime.invoke(entity,now);
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
        }
        else if (operationType == OperationType.UPDATE)
        {
            try
            {
                //反射获取实体参数的setUpdateTime方法
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                setUpdateTime.invoke(entity,now);
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
        }
    }
}
